package com.chatplus.application.aiprocessor.channel.img;

import cn.hutool.http.HttpRequest;
import com.chatplus.application.aiprocessor.constant.AIConstants;
import com.chatplus.application.common.exception.BadRequestException;
import com.chatplus.application.common.logging.SouthernQuietLogger;
import com.chatplus.application.common.logging.SouthernQuietLoggerFactory;
import com.chatplus.application.domain.dto.ChatConfigDto;
import com.chatplus.application.domain.dto.extend.ImgResultDto;
import com.chatplus.application.domain.entity.basedata.ApiKeyEntity;
import com.chatplus.application.domain.vo.file.UpLoadFileVo;
import com.chatplus.application.enumeration.ImgAiPlatformEnum;
import com.chatplus.application.service.basedata.ApiKeyService;
import com.chatplus.application.service.basedata.ConfigService;
import com.chatplus.application.service.file.FileService;
import com.chatplus.application.service.provider.FileServiceProvider;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Base64;
import java.util.List;

/**
 * Img 类型 AI 处理器服务接口
 */
public abstract class ImgAiProcessorService {
    private static final SouthernQuietLogger LOGGER = SouthernQuietLoggerFactory.getLogger(ImgAiProcessorService.class);
    private ConfigService configService;
    private ApiKeyService apiKeyService;
    private FileServiceProvider fileServiceProvider;

    private String apiUrl;
    private List<String> apiKeyList;
    private String errMsg;

    public String getErrMsg() {
        return errMsg;
    }

    private ChatConfigDto.CommonSettingBean commonSetting;

    public ChatConfigDto.CommonSettingBean getCommonSetting() {
        return commonSetting;
    }

    public String getApiUrl() {
        return apiUrl;
    }

    public List<String> getApiKeyList() {
        return apiKeyList;
    }

    @Autowired
    public void setConfigService(ConfigService configService) {
        this.configService = configService;
    }

    @Autowired
    public void setApiKeyService(ApiKeyService apiKeyService) {
        this.apiKeyService = apiKeyService;
    }

    @Autowired
    public void setFileServiceProvider(FileServiceProvider fileServiceProvider) {
        this.fileServiceProvider = fileServiceProvider;
    }

    public abstract ImgResultDto process(String prompt);

    /**
     * AI 渠道处理器
     */
    public abstract ImgAiPlatformEnum getChannel();

    public void initConfig() {
        ChatConfigDto chatConfigDto = configService.getChatConfig();
        ChatConfigDto.CommonSettingBean commonSettingBean = chatConfigDto.getChatGml();
        if (commonSettingBean == null) {
            errMsg = "加载系统配置失败，连接已关闭！！！";
            return;
        }
        this.commonSetting = commonSettingBean;
        List<ApiKeyEntity> apiKeys = apiKeyService.getEnableApiKeys(getChannel().getValue(), "img");
        // // 更新 API KEY 的最后使用时间
        if (CollectionUtils.isEmpty(apiKeys)) {
            errMsg = "抱歉😔😔😔，系统已经没有可用的 API KEY，请联系管理员！";
            return;
        }
        // TODO 这个后续可以考虑弄成多个配置，做轮询
        this.apiKeyList = apiKeys.stream().map(ApiKeyEntity::getValue).filter(StringUtils::isNotEmpty).toList();
        if (CollectionUtils.isEmpty(apiKeyList)) {
            errMsg = "抱歉😔😔😔，系统已经没有可用的 API KEY，请联系管理员！";
            return;
        }
        ApiKeyEntity apiKeyEntity = apiKeys.getFirst();
        this.apiUrl = AIConstants.DefaultBaseUrl.getDefaultBaseUrlByIMGChannel(getChannel());
        if (apiKeyEntity.getUseProxy() == Boolean.TRUE) {
            this.apiUrl = apiKeyEntity.getApiUrl();
        }
    }

    // 保存到OSS
    public String saveToOss(String url, String base64) throws IOException {
        InputStream inputStream = null;
        if (StringUtils.isNotEmpty(base64)) {
            inputStream = base2InputStream(base64);
        }
        if (inputStream == null && StringUtils.isNotEmpty(url)) {
            inputStream = HttpRequest.get(url).execute().bodyStream();
        }
        if (inputStream == null) {
            LOGGER.message("文件上传失败").error();
            throw new BadRequestException("文件上传失败");
        }
        MultipartFile cMultiFile = new MockMultipartFile("file", "ai.png", MediaType.MULTIPART_FORM_DATA_VALUE, inputStream);
        FileService fileService = fileServiceProvider.getFileService(fileServiceProvider.getActiveFileDriver());
        UpLoadFileVo upLoadFileVo = fileService.uploadFile(cMultiFile);
        return upLoadFileVo.getUrl();
    }

    /**
     * base64转inputStream
     */
    private static InputStream base2InputStream(String base64string) {
        ByteArrayInputStream stream = null;
        try {
            byte[] bytes = Base64.getDecoder().decode(base64string);
            stream = new ByteArrayInputStream(bytes);
        } catch (Exception e) {
            return null;
        }
        return stream;
    }
}
